package com.panovue.dataextraction;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;

import java.io.File;
import java.io.IOException;

@Slf4j
public class ReaderUtil {
    public static String baseDir = "C:\\Project\\dataExtraction\\temp\\";

    public static void saveImage(WebElement mainTable, String imageName) {
        File elementScreenshot = mainTable.getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(elementScreenshot, new File(imageName + ".png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveImage(WebDriver driver, String xpath, String name) {
        File elementScreenshot = driver.findElement(By.xpath(xpath)).getScreenshotAs(OutputType.FILE);
        try {
            FileUtils.copyFile(elementScreenshot, new File(name + ".png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void saveFile(String url, String name) {
        log.info("download file ：url {} path {}", url, name);
        long size = HttpUtil.downloadFile(url, name);
        log.info("download {} complete!  size {}", name, size);
    }

    public static void removeElementByXPath(WebDriver driver, String xPath) {
        WebElement element = driver.findElement(By.xpath(xPath));
        ((JavascriptExecutor) driver).executeScript("arguments[0].parentNode.removeChild(arguments[0]);", element);
    }

    public static void removeElementById(WebDriver driver, String id) {
        WebElement element = driver.findElement(By.id(id));
        ((JavascriptExecutor) driver).executeScript("arguments[0].parentNode.removeChild(arguments[0]);", element);
    }
}
